package com.yx.cloud.fragment;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.airbnb.lottie.LottieAnimationView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.iot.common.utils.Event;
import com.iot.common.utils.LogUtils;
import com.iot.product.sweeper.bean.BaseStation;
import com.iot.product.sweeper.bean.Robot;
import com.iot.sweeper.AppContext;
import com.iot.sweeper.param.BaseStationSettingParam;
import com.yx.cloud.MyApplication;
import com.yx.cloud.R;
import com.yx.cloud.activity.MainActivity2;
import com.yx.cloud.activity.MusicCateListActivity;
import com.yx.cloud.activity.MusicPlayingActivity;
import com.yx.cloud.base.LazyLoadFragment;
import com.yx.cloud.bean.RobotIconColorBean;
import com.yx.cloud.constant.Constants;
import com.yx.cloud.product.ProductConfigConstants;
import com.yx.cloud.product.laser.inxni.INXNIConstant;
import com.yx.cloud.product.sdk.tmall.AliGenieSdk;
import com.yx.cloud.product.sdk.tmall.DeviceStatus;
import com.yx.cloud.product.sdk.tmall.MusicInfo;
import com.yx.cloud.utils.AppUtil;
import com.yx.cloud.utils.CommonConfirmDialog2;
import com.yx.cloud.utils.DensityUtil;
import com.yx.cloud.utils.DisplayUtil;
import com.yx.cloud.utils.Intent_utils;
import com.yx.cloud.utils.RomUtils;
import com.yx.cloud.utils.SharedPreferencesList;
import com.yx.cloud.utils.SharedPrefsUtil;
import com.yx.cloud.utils.ToastUtil;
import com.yx.cloud.view.GradientBackgroundView;
import com.yx.cloud.view.HSVColorPickerView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.SoftReference;
import java.util.List;

public class BaseStationFragment extends LazyLoadFragment implements View.OnClickListener {
    private final static String TAG = "BaseStationFragment";
    private static final int MSG_START_IN_1 = 401;
    private static final int MSG_START_IN_2 = 402;
    private static final int MSG_START_OUT_1 = 403;
    private static final int MSG_START_OUT_2 = 404;
    public Dialog baseGuideDialog;
    public LinearLayout baseStationGuideLayout01, baseStationGuideLayout02, baseStationGuideLayout04;
    public RelativeLayout baseStationGuideLayout03;
    private boolean isFolding = false;
    private MainActivity2 activity;
    private ImageView mIvLightSettings, mIvPurifySettings, mIvMusicList,
            mIvMusicListSettings, mIvPreviousSong, mIvNextSong, iv_baseStationSwitchRobot_Icon, ivPlayMusic,
            iv_closeLightSettings, iv_closeAircleanerSettings, mIvGrayBg, mIvRedBg, bs_preview, iv_base_customerServiceIcon, mIvWhiteBg, mIvBlueBg, mIvPinkBg;

    private CheckBox mCbLightSwitch, mCbPurifySwitch;
    private ConstraintLayout cl_air_quality;
    private TextView mTvPm, mTvAirQuality, tv_aircleanerFilterType;
    private LottieAnimationView lav_aircleaner_in, lav_aircleaner_in_2, lav_aircleaner_out, lav_aircleaner_out_2;
    private LinearLayout mLlPm25Color;
    private ConstraintLayout lightSettings, aircleanerSettings, mainBottom;
    private Robot robot;
    private Handler handler;
    private HSVColorPickerView hsvColorPickerView;
    private RadioGroup rg_lightType, rg_aircleaner;
    private RadioButton rb_light_white, rb_light_colorful, rb_light_rainbow, rb_aircleaner1, rb_aircleaner2, rb_aircleaner3, rb_aircleaner4;
    private SeekBar sb_aircleanerLife;
    private CheckBox cbx_plasma;
    private GradientBackgroundView v_light_color_bg;
    private PopupWindow popupWindow;
    private String switch_icon = "white";
    private int aliGenieStatus = 1;//默认天猫在线
    private boolean uiVisible = false;
    private int currentItem;
    private String deviceTag, tmallDeviceId;
    private JSONObject productConfig;

    public BaseStationFragment() {
        super();
    }

    public static BaseStationFragment newInstance(Bundle args) {
        BaseStationFragment f = new BaseStationFragment();
        f.setArguments(args);
        return f;
    }

    public String getDeviceTag() {
        return deviceTag;
    }

    public void setDeviceTag(String deviceTag) {
        this.deviceTag = deviceTag;
    }

    @Override
    protected int setContentView() {
        return R.layout.base_station_fragment;
    }

    @Override
    public void onPageSelect(int position) {
        super.onPageSelect(position);
        LogUtils.i("BaseStation onPageSelect ");
        currentItem = position;
        initData();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopAliGenieRequest();
    }

    @Override
    public void onPageUnselect(int position) {
        super.onPageUnselect(position);
        LogUtils.i(" BaseStation onPageUnselect");
        switchAirCleanerAnim(false);
        stopAliGenieRequest();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        robot = AppContext.get().getCurrentDevice();
        initView();
        initData();
        return view;
    }

    private void initView() {
        Log.d(TAG, " : BaseStationFragment======initView========= : ");
        handler = new MainHandler(this);
        activity = (MainActivity2) getActivity();
        mainBottom = findViewById(R.id.main_bottom);
        bs_preview = findViewById(R.id.bs_preview);

        initAircleanerView();
        initLightView();

        iv_baseStationSwitchRobot_Icon = findViewById(R.id.iv_baseStationSwitchRobot_Icon);
        iv_base_customerServiceIcon = findViewById(R.id.iv_base_customerServiceIcon);

        mIvMusicList = findViewById(R.id.iv_musicList);//音乐列表
        mIvMusicListSettings = findViewById(R.id.iv_musicListSettings);//音乐列表设置
        mIvPreviousSong = findViewById(R.id.iv_previous_song);//上一首
        mIvNextSong = findViewById(R.id.iv_next_song);//上一首
        ivPlayMusic = findViewById(R.id.iv_play_music);//播放

        mTvPm = findViewById(R.id.tv_pm);//PM2.5
        cl_air_quality = findViewById(R.id.cl_air_quality);
        mTvAirQuality = findViewById(R.id.tv_airQuality);//空气质量
        mLlPm25Color = findViewById(R.id.ll_pm25_color);//空气质量颜色条
        v_light_color_bg = findViewById(R.id.v_light_color_bg);

        productConfig = robot.getConfig();

        //基站切换机器图片
        DisplayUtil.show(iv_baseStationSwitchRobot_Icon, productConfig.optBoolean(ProductConfigConstants.x5BaseStationHasMultiStyle));
        // Constants.switchRobotIcon_view = bs_preview;
        mainBottom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                foldAnim(lightSettings, 300);
                foldAnim(aircleanerSettings, 300);
            }
        });

        mIvMusicList.setOnClickListener(this);
        mIvMusicListSettings.setOnClickListener(this);
        mIvPreviousSong.setOnClickListener(this);
        mIvNextSong.setOnClickListener(this);
        iv_baseStationSwitchRobot_Icon.setOnClickListener(this);
        iv_base_customerServiceIcon.setOnClickListener(this);

    }

    private void initData() {
        LogUtils.i("=============== initData");
        //根据扫地机获取对应天猫的设备ID
        tmallDeviceId = robot.getTmalDeviceId();
        INXNIConstant.DEVICE_ID = tmallDeviceId;
        SharedPrefsUtil.putValue(activity, Constants.DEVICEID, "deviceId", robot.getDeviceId());
        SharedPrefsUtil.putValue(activity, "USER_DEVICE_ID", "user_device_id", tmallDeviceId);
        SharedPrefsUtil.putValue(activity, "LAST_SELECTION_ROBOT_TYPE", "last_selection_robot_type", 1);
        int value = SharedPrefsUtil.getValue(activity, "LAST_SELECTION_ROBOT_TYPE", "last_selection_robot_type", 0);
        LogUtils.i(value + " : =======天猫精灵设备ID ======== tmallDeviceId : " + tmallDeviceId);
        activity.binding.ivRightMenu.setVisibility(View.INVISIBLE);

        activity.isMianShow = false;
        activity.mMesListData.clear();//消息列表
        activity.binding.mainMesList.setVisibility(View.GONE);//消息列表
        if (Constants.UpdateLayout != null) {
            Constants.UpdateLayout.setVisibility(View.GONE);//升级布局
        }
        currentItem = activity.binding.mMainViewPager.getCurrentItem();
        getRobotAirview(robot);
        mLlPm25Color.setVisibility(View.VISIBLE);//PM2.5颜色条
        BaseStation baseStation = robot.getBaseStation();
        setBaseStationInfo(baseStation);
        aliGenieStatus = 1;
        ivPlayMusic.setOnClickListener(this);
        //操作引导界面
        setGuideInterface();

    }

    private void initLightView() {
        mCbLightSwitch = findViewById(R.id.cb_lightSwitch);
        mCbLightSwitch.setOnClickListener(this);

        mIvLightSettings = findViewById(R.id.iv_lightSettings);//灯光更多设置
        mIvLightSettings.setOnClickListener(this);
        lightSettings = findViewById(R.id.layout_x5_basestation_light);
        lightSettings.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        rg_lightType = findViewById(R.id.rg_x5_bs_light_type);
        rb_light_white = findViewById(R.id.rb_x5_bs_light_white);
        rb_light_colorful = findViewById(R.id.rb_x5_bs_light_colorful);
        rb_light_rainbow = findViewById(R.id.rb_x5_bs_light_rainbow);
        rb_light_white.setOnClickListener(this);
        rb_light_colorful.setOnClickListener(this);
        rb_light_rainbow.setOnClickListener(this);


        iv_closeLightSettings = findViewById(R.id.iv_close_light_setting);
        iv_closeLightSettings.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                foldAnim(lightSettings, 300);
            }
        });

        hsvColorPickerView = findViewById(R.id.hsv_color_picker);
        hsvColorPickerView.setEventListener(new HSVColorPickerView.TouchEventListener() {
            @Override
            public void onEventHandle(boolean isUsing) {
                activity.binding.mMainViewPager.setNoScroll(isUsing);
            }
        });
        hsvColorPickerView.setOnLightSelectedListener(new HSVColorPickerView.LightChangeListener() {

            public void onLightChange(float[] hsv, boolean changed) {
                BaseStation baseStation = AppContext.get().getCurrentDevice().getBaseStation();
                if (hsvColorPickerView.getMode() == BaseStation.LIGHT_TYPE_COLORFUL) {
                    v_light_color_bg.setColor(hsv, BaseStation.LIGHT_TYPE_COLORFUL);

                    if (changed) {
                        BaseStationSettingParam baseStationParam = BaseStationSettingParam.newBuilder().light(mCbLightSwitch.isChecked(), BaseStation.LIGHT_TYPE_COLORFUL, Color.HSVToColor(hsv), baseStation.getBrightness()).build();
                        AppContext.getProductService().setBaseStationSetting(baseStationParam);
                    }

                } else if (hsvColorPickerView.getMode() == BaseStation.LIGHT_TYPE_WHITE) {
                    float brightness = hsv[2];
                    v_light_color_bg.setColor(hsv, BaseStation.LIGHT_TYPE_WHITE);

                    if (changed) {
                        BaseStationSettingParam baseStationParam = BaseStationSettingParam.newBuilder().light(mCbLightSwitch.isChecked(), BaseStation.LIGHT_TYPE_WHITE, baseStation.getLightColor(), (int) (brightness * 100)).build();
                        AppContext.getProductService().setBaseStationSetting(baseStationParam);
                    }
                }
            }
        });
    }

    private void initAircleanerView() {
        sb_aircleanerLife = findViewById(R.id.sb_x5_bs_airfilter_life);
        sb_aircleanerLife.setEnabled(false);

        cbx_plasma = findViewById(R.id.cbx_x5_bs_aircleaner_plasma_switcher);
        cbx_plasma.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                BaseStationSettingParam param = BaseStationSettingParam.newBuilder().plasmaSwitch(cbx_plasma.isChecked()).build();
                AppContext.getProductService().setBaseStationSetting(param);
            }
        });

        rg_aircleaner = findViewById(R.id.rg_x5_bs_aircleaner);
        rb_aircleaner1 = findViewById(R.id.rb_x5_bs_aircleaner_1);
        rb_aircleaner1.setOnClickListener(this);
        rb_aircleaner2 = findViewById(R.id.rb_x5_bs_aircleaner_2);
        rb_aircleaner2.setOnClickListener(this);
        rb_aircleaner3 = findViewById(R.id.rb_x5_bs_aircleaner_3);
        rb_aircleaner3.setOnClickListener(this);
        rb_aircleaner4 = findViewById(R.id.rb_x5_bs_aircleaner_4);
        rb_aircleaner4.setOnClickListener(this);

        iv_closeAircleanerSettings = findViewById(R.id.iv_close_aircleaner_setting);
        iv_closeAircleanerSettings.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                foldAnim(aircleanerSettings, 300);
            }
        });

        aircleanerSettings = findViewById(R.id.layout_x5_basestation_aircleaner);
        aircleanerSettings.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //消耗掉事件  不传递到上层导致关闭对话框
            }
        });

        tv_aircleanerFilterType = findViewById(R.id.rb_x5_bs_aircleaner_type);
        tv_aircleanerFilterType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                CommonConfirmDialog2.newBuilder().context(getContext()).message(getString(R.string.H_Ap_Filter_Reset)).confirmCallback(new CommonConfirmDialog2.ConfirmCallback() {
                    @Override
                    public boolean onConfirm() {
                        BaseStation baseStation = AppContext.get().getCurrentDevice().getBaseStation();
                        BaseStationSettingParam param = BaseStationSettingParam.newBuilder().setResetFilter(baseStation.getAirFilterType()).build();
                        AppContext.getProductService().setBaseStationSetting(param);
                        return true;
                    }

                    @Override
                    public boolean onCancel() {
                        return true;
                    }
                }).build().show();
            }
        });

        mCbPurifySwitch = findViewById(R.id.cb_purifySwitch);
        mCbPurifySwitch.setOnClickListener(this);
        mIvPurifySettings = findViewById(R.id.iv_purifySettings);//净化更多设置
        mIvPurifySettings.setOnClickListener(this);
        lav_aircleaner_in = findViewById(R.id.lav_x5_air_in);
        lav_aircleaner_in_2 = findViewById(R.id.lav_x5_air_in_2);
        lav_aircleaner_out = findViewById(R.id.lav_x5_air_out);
        lav_aircleaner_out_2 = findViewById(R.id.lav_x5_air_out_2);
    }

    private void setAirQuality(int i) {
        if (i == 0) {
            mTvAirQuality.setText(activity.getResources().getString(R.string.H_Excellent));
            mLlPm25Color.setBackground(activity.getResources().getDrawable(R.mipmap.shape_pm_rectangle_excellent));
        } else if (i == 1) {
            mTvAirQuality.setText(activity.getResources().getString(R.string.H_Medium));
            mLlPm25Color.setBackground(activity.getResources().getDrawable(R.mipmap.shape_pm_rectangle_middle));
        } else if (i == 2) {
            mTvAirQuality.setText(getString(R.string.H_Poor));
            mLlPm25Color.setBackground(activity.getResources().getDrawable(R.mipmap.shape_pm_rectangle_difference));
        }
    }

    @Override
    public void onClick(View v) {
        if (RomUtils.isFastClick()) {
            return;
        }
        int id = v.getId();
        BaseStation baseStation = AppContext.get().getCurrentDevice().getBaseStation();
        if (id == R.id.iv_lightSettings) {
            //灯光更多设置
            if (baseStation.isBaseStationIsOnLine()) {
                unfoldAnim(lightSettings, 300);
                if (!baseStation.isLightSwitch()) {
                    int brightness = baseStation.getBrightness() < 1 ? 1 : baseStation.getBrightness();
                    rg_lightType.check(R.id.rb_x5_bs_light_white);
                    hsvColorPickerView.setBrightness(brightness / 100f);
                    hsvColorPickerView.setColor(baseStation.getLightColor());
                    BaseStationSettingParam baseStationParam = BaseStationSettingParam.newBuilder().light(true, BaseStation.LIGHT_TYPE_WHITE, 0xFF5520DF, brightness).build();
                    AppContext.getProductService().setBaseStationSetting(baseStationParam);
                }
            } else {
                showBaseStationOfflineDialog();
            }
        } else if (id == R.id.iv_purifySettings) {
            if (baseStation.isBaseStationIsOnLine()) {
                unfoldAnim(aircleanerSettings, 300);
            } else {
                showBaseStationOfflineDialog();
            }

        } else if (id == R.id.iv_musicList) {
            if (aliGenieStatus == 0) {
                aliGenieOfflineTipDialog(getString(R.string.H_Host_Offline), getString(R.string.H_Host_Offline_Tip));
                return;
            }
            Intent_utils.enterIntentFromBottom(getActivity(), MusicCateListActivity.class);
        } else if (id == R.id.iv_musicListSettings) {
            if (aliGenieStatus == 0) {
                aliGenieOfflineTipDialog(getString(R.string.H_Host_Offline), getString(R.string.H_Host_Offline_Tip));
                return;
            }
            Intent_utils.enterIntentFromBottom(getActivity(), MusicPlayingActivity.class);
        } else if (id == R.id.iv_previous_song) {
            if (aliGenieStatus == 0) {
                aliGenieOfflineTipDialog(getString(R.string.H_Host_Offline), getString(R.string.H_Host_Offline_Tip));
                return;
            }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    previousAndNextControl("PREVIOUS");
                }
            }).start();
        } else if (id == R.id.iv_next_song) {
            if (aliGenieStatus == 0) {
                aliGenieOfflineTipDialog(getString(R.string.H_Host_Offline), getString(R.string.H_Host_Offline_Tip));
                return;
            }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    previousAndNextControl("NEXT");
                }
            }).start();

        } else if (id == R.id.iv_play_music) {
            if (aliGenieStatus == 0) {
                aliGenieOfflineTipDialog(getString(R.string.H_Host_Offline), getString(R.string.H_Host_Offline_Tip));
                return;
            }
            DeviceStatus deviceStatus = AliGenieSdk.get().getCurrentMusic();
            if (deviceStatus != null) {
                if (deviceStatus.getMusicInfo().getMusicPlayStatus().equals("play")) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            playAndPause("Pause");
                            Log.d("music", "====================play");
                        }
                    }).start();
                } else {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            playAndPause("Play");
                            Log.d("music", "====================play");
                        }
                    }).start();
                }
            }
        } else if (id == R.id.cb_lightSwitch) {
            if (baseStation.isBaseStationIsOnLine()) {
                BaseStationSettingParam baseStationParam = BaseStationSettingParam.newBuilder()
                        .light(mCbLightSwitch.isChecked(), baseStation.getLightType(),
                                baseStation.getLightColor(),
                                baseStation.getBrightness())
                        .build();
                AppContext.getProductService().setBaseStationSetting(baseStationParam);
            } else {
                showBaseStationOfflineDialog();
            }
            mCbLightSwitch.setChecked(!mCbLightSwitch.isChecked());
        } else if (id == R.id.cb_purifySwitch) {
            if (baseStation.isBaseStationIsOnLine()) {
                AppContext.getProductService().setBaseStationSetting(BaseStationSettingParam.newBuilder().airCleanerSwitch(mCbPurifySwitch.isChecked()).build());
            } else {
                showBaseStationOfflineDialog();
            }
            mCbPurifySwitch.setChecked(!mCbPurifySwitch.isChecked());
        } else if (id == R.id.rb_x5_bs_aircleaner_1 || id == R.id.rb_x5_bs_aircleaner_2 || id == R.id.rb_x5_bs_aircleaner_3 || id == R.id.rb_x5_bs_aircleaner_4) {
            int airCleaner = getCheckedAirCleaner();
            BaseStationSettingParam baseStationParam = BaseStationSettingParam.newBuilder().airCleaner(airCleaner).build();
            AppContext.getProductService().setBaseStationSetting(baseStationParam);
        } else if (id == R.id.rb_x5_bs_light_white || id == R.id.rb_x5_bs_light_colorful || id == R.id.rb_x5_bs_light_rainbow) {
            int lightType = getCheckedLightType();
            hsvColorPickerView.setMode(lightType);
            v_light_color_bg.setColor(lightType);
            if (lightType == BaseStation.LIGHT_TYPE_COLORFUL) {
                baseStation.setLightColor(0xFF5520DF);
            }
            BaseStationSettingParam baseStationParam = BaseStationSettingParam.newBuilder().light(true, lightType, baseStation.getLightColor(), baseStation.getBrightness()).build();
            AppContext.getProductService().setBaseStationSetting(baseStationParam);
        } else if (id == R.id.iv_baseStationSwitchRobot_Icon) {
            switchRobotIcon();
        } else if (id == R.id.iv_base_customerServiceIcon) {
            boolean wxPk = AppUtil.isPkgInstalled(activity, "com.tencent.mm");
            if (wxPk) {
                Intent_utils.gotoShop(activity, "http://isemall.cn/efYNZv2aC");
            } else {
                Toast.makeText(activity, getString(R.string.install_WeChat), Toast.LENGTH_LONG).show();
            }
        }

    }

    private void previousAndNextControl(String cmd) {
        AliGenieSdk.get().previousAndNext(cmd);
    }

    private void playAndPause(String cmd) {
        AliGenieSdk.get().playAndPause(cmd);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Event event) {
        //  Log.d(TAG, " : onEventMainThread============== : "+event.toString());
        Robot current = AppContext.get().getCurrentDevice();
        if (current == null || !robot.getDeviceId().equals(current.getDeviceId())) {
            return;
        }
        if (event.getType() == Event.MSG_ROBOT_STATE) {
            LogUtils.i(" : BaseStationFragment======MSG_ROBOT_STATE MSG_ROBOT_STATE MSG_ROBOT_STATE========= : ");
        } else if (event.getType() == Event.MEG_ROBOT_BASESTATION_LIGHT) {
            BaseStation baseStation = (BaseStation) event.getContent();
            setBSLight(baseStation);
        } else if (event.getType() == Event.MEG_ROBOT_BASESTATION_AIRCLEAN) {
            BaseStation baseStation = (BaseStation) event.getContent();
            setBSAirCleaner(baseStation);
        } else if (event.getType() == Event.MEG_ROBOT_BASESTATION_STATE) {
            BaseStation baseStation = (BaseStation) event.getContent();
            // setBSState(baseStation);

            if (baseStation.isBaseStationIsOnLine()) {
                startAliGenieRequest();
            } else {
                stopAliGenieRequest();
            }
        } else if (event.getType() == Event.MESSAGE_TYPE_GET_DEVICE_STATUS_DETAIL) {
            if (event.isResult()) {
                DeviceStatus deviceStatus = (DeviceStatus) event.getContent();
                AliGenieSdk.get().setCurrentMusic(deviceStatus);
                if (deviceStatus.getMusicInfo().getMusicPlayStatus().equals("play")) {
                    ivPlayMusic.setImageResource(R.mipmap.pause_music_icon);
                } else {
                    ivPlayMusic.setImageResource(R.mipmap.play_music_icon);
                }
            } else {
                String message = (String) event.getContent();
                Log.i(TAG, "设备状态详情" + message);
                //ToastUtil.show(getActivity(), message, Toast.LENGTH_SHORT);
            }
        } else if (event.getType() == Event.MESSAGE_TYPE_PLAY_AND_PAUSE || event.getType() == Event.MESSAGE_TYPE_INDEX_PLAY_MUSIC || event.getType() == Event.MESSAGE_TYPE_PREVIOUS_AND_NEXT_CONTROL) {
            if (!event.isResult()) {
                String msg = (String) event.getContent();
                ToastUtil.show(getActivity(), msg, Toast.LENGTH_SHORT);
            } else {
                if (event.getType() == Event.MESSAGE_TYPE_PREVIOUS_AND_NEXT_CONTROL) {
                    String cmd = (String) event.getExtra();
                    MusicInfo musicInfo = (MusicInfo) event.getContent();
                    if (musicInfo == null) {
                        if (cmd.equals("NEXT")) {
                            ToastUtil.show(getActivity(), getString(R.string.M_T_Last), Toast.LENGTH_SHORT);
                        } else {
                            ToastUtil.show(getActivity(), getString(R.string.M_T_First), Toast.LENGTH_SHORT);
                        }
                    }
                }
            }
        }
//        else if (event.getType() == Event.MESSAGE_TYPE_DELETE_EQUIPMENT) {
        //删除设备
//            if (Constants.FLAVOR_INXNI.equals(BuildConfig.FLAVOR)) {
//                /**
//                 * 切换机器人图片保存对应的key
//                 */
//                SharedPreferencesList.switchRobotPicture(activity, "delete", "", application.deviceListData_local);
//            }
        // Constants.isRerun = false;
//            AppContext.getAccountService().getDeviceList();//获取设备列表
//            Log.i(TAG, "BaseStationFragment 删除设备:::::::::::::::::::::::::::::::::::xxxxxx ");
//        }
//        else if (event.getType() == Event.MESSAGE_TYPE_GET_DEVICE_LIST) {
//            List newDeviceList = (List<Robot>) event.getContent();
//            Log.i(TAG, "onEventMainThread: llllllllllllllllllllll ： " + newDeviceList.size());
//            // Constants.isRerun = false;
//            activity.handleDeviceList(newDeviceList, "base");
//        }
        else if (event.getType() == Event.MESSAGE_TYPE_GET_DEVICE_STATUS) {
            if (event.isResult()) {
                int deviceStatus = (int) event.getContent();
                aliGenieStatus = deviceStatus;
            }
        }
    }

//    private void setBSState(BaseStation baseStation) {
//        airCleaerFault(baseStation);
//    }

    private void aliGenieOfflineTipDialog(String dialogTitle, String content) {
        Dialog dialog = new Dialog(activity);
        dialog.setContentView(R.layout.outlogin_dialog);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        dialog.setCanceledOnTouchOutside(false);
        TextView mBtnOutLoginConfirm = dialog.findViewById(R.id.btn_outLoginConfirm);
        TextView mBtnOutLoginCancel = dialog.findViewById(R.id.btn_outLoginCancel);
        TextView mTvDialogTitle = dialog.findViewById(R.id.tv_dialogTitle);
        TextView mTvDialogContent = dialog.findViewById(R.id.tv_content);
        View vLine = dialog.findViewById(R.id.main_view);
        mTvDialogTitle.setText(dialogTitle);
        mTvDialogContent.setText(content);
        mBtnOutLoginConfirm.setText(getString(R.string.U_IKnow_Btn));
        mBtnOutLoginConfirm.setTextColor(activity.getColor(R.color.text_color_blue));
        mBtnOutLoginCancel.setVisibility(View.GONE);
        vLine.setVisibility(View.GONE);
        mBtnOutLoginConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private void setBSAirCleaner(BaseStation baseStation) {

        cbx_plasma.setChecked(baseStation.isPlasmaSwitch());

        setAirQuality(baseStation.getAirQuality());
        mTvPm.setText("" + baseStation.getPm25());

        if (mCbPurifySwitch.isChecked()) {
            mTvPm.setVisibility(View.VISIBLE);
            cl_air_quality.setVisibility(View.VISIBLE);
        } else {
            mTvPm.setVisibility(View.GONE);
            cl_air_quality.setVisibility(View.GONE);
        }

        if (mCbPurifySwitch.isChecked() != baseStation.getAirCleanerSwitch()) {
            //如果和之前状态相同 就不处理
            switchAirCleanerAnim(baseStation.getAirCleanerSwitch());
        }

        mCbPurifySwitch.setChecked(baseStation.getAirCleanerSwitch());

        if (baseStation.getAirFilterType() == BaseStation.AIR_FILTER_HCHO) {
            tv_aircleanerFilterType.setText(R.string.H_Ap_Filter_CH2O);
            sb_aircleanerLife.setProgress(baseStation.getHchoAirCleanerLife());
        } else {
            tv_aircleanerFilterType.setText(R.string.H_Ap_Filter_Standard);
            sb_aircleanerLife.setProgress(baseStation.getAirCleanerLife());
        }

        rg_aircleaner.clearCheck();
        rg_aircleaner.check(getAirCleanerButtonId(baseStation.getAirCleaner()));
    }

    private void setBaseStationInfo(BaseStation baseStation) {
        setBSLight(baseStation);
        setBSAirCleaner(baseStation);
        // setBSState(baseStation);
    }

    private void setBSLight(BaseStation baseStation) {
        int type = baseStation.getLightType();
        float progress = baseStation.getBrightness() / 100f;
        if (type == BaseStation.LIGHT_TYPE_WHITE) {
            v_light_color_bg.setColor(new float[]{0, 1, progress}, type);
        } else {
            float[] hsv = new float[3];
            Color.colorToHSV(baseStation.getLightColor(), hsv);
            v_light_color_bg.setColor(hsv, type);
        }
        mCbLightSwitch.setChecked(baseStation.isLightSwitch());
        v_light_color_bg.setVisibility(baseStation.isLightSwitch() ? View.VISIBLE : View.INVISIBLE);
        hsvColorPickerView.setBrightness(progress);
        hsvColorPickerView.setColor(baseStation.getLightColor());
        hsvColorPickerView.setMode(baseStation.getLightType());

        rg_lightType.clearCheck();
        if (mCbLightSwitch.isChecked()) {
            rg_lightType.check(getLightTypeButtonId(baseStation.getLightType()));
        }
    }

    private void switchAirCleanerAnim(boolean start) {
        LogUtils.i("switchAirCleanerAnim  : " + start);
        if (handler != null) {
            handler.removeMessages(MSG_START_IN_1);
            handler.removeMessages(MSG_START_IN_2);
            handler.removeMessages(MSG_START_OUT_1);
            handler.removeMessages(MSG_START_OUT_2);
        }
        if (start) {
            LogUtils.i(" msg start anim");
            if (handler == null) {
                return;
            }
            handler.sendEmptyMessage(MSG_START_IN_1);
            handler.sendEmptyMessageDelayed(MSG_START_OUT_1, 3000);
        } else {
            LogUtils.i(" msg clear anim");
            if (lav_aircleaner_in != null) {
                //无意间发现  划到了fragment竟然会先调用onPause 神奇  这个时候lazyload还没加载好 崩....
                lav_aircleaner_in.setProgress(0);
                lav_aircleaner_in_2.setProgress(0);
                lav_aircleaner_out.setProgress(0);
                lav_aircleaner_out_2.setProgress(0);
                lav_aircleaner_in.cancelAnimation();
                lav_aircleaner_in_2.cancelAnimation();
                lav_aircleaner_out.cancelAnimation();
                lav_aircleaner_out_2.cancelAnimation();
            }
        }
    }

    private void startAliGenieRequest() {
        if (handler != null) {
            handler.removeMessages(Event.MESSAGE_TYPE_GET_DEVICE_STATUS_DETAIL_REPEAT);
            handler.removeMessages(Event.MESSAGE_TYPE_GET_DEVICE_STATUS_INFO);
            handler.sendEmptyMessage(Event.MESSAGE_TYPE_GET_DEVICE_STATUS_DETAIL_REPEAT);
            handler.sendEmptyMessage(Event.MESSAGE_TYPE_GET_DEVICE_STATUS_INFO);
        }
    }

    private void stopAliGenieRequest() {
        if (handler != null) {
            handler.removeMessages(Event.MESSAGE_TYPE_GET_DEVICE_STATUS_DETAIL_REPEAT);
            handler.removeMessages(Event.MESSAGE_TYPE_GET_DEVICE_STATUS_INFO);
        }
    }

    private int getLightTypeButtonId(int lightType) {
        if (lightType == BaseStation.LIGHT_TYPE_COLORFUL) {
            return R.id.rb_x5_bs_light_colorful;
        } else if (lightType == BaseStation.LIGHT_TYPE_RAINBOW) {
            return R.id.rb_x5_bs_light_rainbow;
        } else {
//            BaseStation.LIGHT_TYPE_WHITE
            return R.id.rb_x5_bs_light_white;
        }
    }

    private int getCheckedLightType() {
        int checkedId = rg_lightType.getCheckedRadioButtonId();
        int lightType;
        if (checkedId == R.id.rb_x5_bs_light_colorful) {
            lightType = BaseStation.LIGHT_TYPE_COLORFUL;
        } else if (checkedId == R.id.rb_x5_bs_light_rainbow) {
            lightType = BaseStation.LIGHT_TYPE_RAINBOW;
        } else {
//             R.id.rb_x5_bs_light_white
            lightType = BaseStation.LIGHT_TYPE_WHITE;
        }
        return lightType;

    }

    private int getCheckedAirCleaner() {
        int checkedId = rg_aircleaner.getCheckedRadioButtonId();
        if (checkedId == R.id.rb_x5_bs_aircleaner_1) {
            return 1;
        } else if (checkedId == R.id.rb_x5_bs_aircleaner_3) {
            return 3;
        } else if (checkedId == R.id.rb_x5_bs_aircleaner_4) {
            return 4;
        } else {
//          rb_x5_bs_aircleaner_2  默认自动挡
            return 2;
        }
    }

    private int getAirCleanerButtonId(int airCleaner) {
        if (airCleaner == 1) {
            return R.id.rb_x5_bs_aircleaner_1;
        } else if (airCleaner == 3) {
            return R.id.rb_x5_bs_aircleaner_3;
        } else if (airCleaner == 4) {
            return R.id.rb_x5_bs_aircleaner_4;
        } else {
//          auto 2
            return R.id.rb_x5_bs_aircleaner_2;
        }
    }

    private void getDeviceStatusInfo() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d("music", "==getDeviceStatusInfo==**");
                AliGenieSdk.get().getDeviceStatusInfo();
            }
        }).start();
        if (handler == null) {
            return;
        }
        handler.removeMessages(Event.MESSAGE_TYPE_GET_DEVICE_STATUS_INFO);
        handler.sendEmptyMessageDelayed(Event.MESSAGE_TYPE_GET_DEVICE_STATUS_INFO, 10000);
    }

    private void getDeviceStatusDetail() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.d("music", "==getDeviceStatusDetail==**");
                AliGenieSdk.get().getDeviceStatusDetail();
            }
        }).start();
        if (handler == null) {
            return;
        }
        handler.removeMessages(Event.MESSAGE_TYPE_GET_DEVICE_STATUS_DETAIL_REPEAT);
        handler.sendEmptyMessageDelayed(Event.MESSAGE_TYPE_GET_DEVICE_STATUS_DETAIL_REPEAT, 3000);
    }

    /**
     * 空气净化故障
     * <p>
     * //     * @param baseStation
     */
//    private void airCleaerFault(BaseStation baseStation) {
//        Log.d(TAG, baseStation.getAirFilterType() + " : 净化故障 寿命 ：" + baseStation.getAirCleanerLife() + " , " + baseStation.getHchoAirCleanerLife());
//        String failt = "恢复正常";
//        int airCleaerFault = baseStation.getAirCleaerFault();
//        if (0 == airCleaerFault) {
//            //正常
//            failt = "恢复正常";
////            if ((baseStation.getAirFilterType() == BaseStation.AIR_FILTER_HCHO && baseStation.getHchoAirCleanerLife() == 0)
////                    || (baseStation.getAirFilterType() == BaseStation.AIR_FILTER_STANDARD && baseStation.getAirCleanerLife() == 0)
////            ) {
////                failt = getString(R.string.replace_filter);
////            }
//        } else if (1 == airCleaerFault) {
//            //点击故障
//            failt = getString(R.string.air_Cleaer_Fault_1);
//        } else if (2 == airCleaerFault) {
//            //灰尘检测传感器故障
//            failt = getString(R.string.air_Cleaer_Fault_2);
//        } else if (3 == airCleaerFault) {
//            //电机与灰尘检测传感器故障
//            failt = getString(R.string.air_Cleaer_Fault_3);
//        }
//        activity.setFaultState(failt, 3, "333");
//    }
    private void getRobotAirview(Robot robot) {
        SharedPreferences sp = MyApplication.get().getSharedPreferences("X5_SP_ROBOT_ICON", Context.MODE_PRIVATE);
        String peopleListJson = sp.getString("X5_KEY_RobotIcon_LIST_DATA", "");
        if (peopleListJson != "")  //防空判断
        {
            Gson gson = new Gson();
            List<RobotIconColorBean> mList = gson.fromJson(peopleListJson, new TypeToken<List<RobotIconColorBean>>() {
            }.getType());
            //LogUtils.i(" BaseStationFragment : onFling fffffffff********** : " + new Gson().toJson(mList));
            if (mList != null) {
                String connect_deviceId = robot.getTmalDeviceId();
                // LogUtils.i(" BaseStationFragment : onFling fffffffff********** connect_deviceId : " + connect_deviceId);
                if (connect_deviceId != null && !connect_deviceId.equals("")) {
                    for (int i = 0; i < mList.size(); i++) {
                        if (mList.get(i).getDeviceId().equals(connect_deviceId)) {
                            String color = mList.get(i).getIsICutoverColor();
                            //Log.d(TAG, " BaseStationFragment : onFling fffffffff 000 : " + color);
                            if (color != null) {
                                if ("gray".equals(color)) {
                                    //LogUtils.i(" BaseStationFragment : onFling fffffffff 1111 : ");
                                    bs_preview.setImageResource(R.mipmap.main_x5_base_station_gray_icon);
                                } else if ("white".equals(color)) {
                                    //LogUtils.i(" BaseStationFragment : onFling fffffffff 22222 : ");
                                    bs_preview.setImageResource(R.mipmap.robot_icon_pic_x5_white);
                                } else if ("blue".equals(color)) {
                                    bs_preview.setImageResource(R.mipmap.main_x5_base_station_gray_icon);
                                } else if ("pink".equals(color)) {
                                    bs_preview.setImageResource(R.mipmap.main_x5_base_station_gray_icon);
                                } else {
                                    //LogUtils.i(" BaseStationFragment : onFling fffffffff 3333 : ");
                                    bs_preview.setImageResource(R.mipmap.main_x5_base_station_gray_icon);
                                }
                            }
                            break;
                        }
                    }
                } else {
                    //LogUtils.i(" BaseStationFragment : onFling fffffffff********** null  null null null ");
                    bs_preview.setImageResource(R.mipmap.main_x5_base_station_gray_icon);
                }
            }
        }
    }

    private void switchRobotIcon() {
        // LogUtils.i(" 切换机器 颜色   switchRobotIcon ");
        LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View contentview = inflater.inflate(R.layout.base_station_switch_robot_icon_popup, null);

        RelativeLayout rlBaseStationSwitchRobotIconGrayLayout = contentview.findViewById(R.id.rl_baseStationSwitchRobotIconGrayLayout);
        RelativeLayout rlBaseStationSwitchRobotIconPinkLayout = contentview.findViewById(R.id.rl_baseStationSwitchRobotIconPinkLayout);
        RelativeLayout rlBaseStationSwitchRobotIconBlueLayout = contentview.findViewById(R.id.rl_baseStationSwitchRobotIconBlueLayout);
        RelativeLayout rlBaseStationSwitchRobotIconWhiteLayout = contentview.findViewById(R.id.rl_baseStationSwitchRobotIconWhiteLayout);

        RadioButton rb_gray = contentview.findViewById(R.id.rb_baseStationSwitchRobotIcon_gray);
        RadioButton rb_pink = contentview.findViewById(R.id.rb_baseStationSwitchRobotIcon_pink);
        RadioButton rb_blue = contentview.findViewById(R.id.rb_baseStationSwitchRobotIcon_blue);
        RadioButton rb_white = contentview.findViewById(R.id.rb_baseStationSwitchRobotIcon_white);
        mIvGrayBg = contentview.findViewById(R.id.iv_gray_bg);
        mIvWhiteBg = contentview.findViewById(R.id.iv_white_bg);
        mIvBlueBg = contentview.findViewById(R.id.iv_blue_bg);
        mIvPinkBg = contentview.findViewById(R.id.iv_pink_bg);
        try {
            JSONArray jsonArray = productConfig.getJSONArray(ProductConfigConstants.robotIconColorSpecies);
            LogUtils.i(jsonArray.length() + ">>>>>>>>>> " + new Gson().toJson(jsonArray));
            String json = new Gson().toJson(jsonArray);
            activity.setVisibility(rlBaseStationSwitchRobotIconWhiteLayout, json.contains(getString(R.string.H_RobotColor_1))); //白
            activity.setVisibility(rlBaseStationSwitchRobotIconPinkLayout, json.contains(getString(R.string.H_RobotColor_2)));  //粉
            activity.setVisibility(rlBaseStationSwitchRobotIconBlueLayout, json.contains(getString(R.string.H_RobotColor_3)));  //蓝
            activity.setVisibility(rlBaseStationSwitchRobotIconGrayLayout, json.contains(getString(R.string.H_RobotColor_4)));  //灰
        } catch (JSONException e) {
            e.printStackTrace();
        }

        switchRobotTextColor(mIvGrayBg, mIvWhiteBg, mIvBlueBg, mIvPinkBg);

        rb_gray.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                mIvGrayBg.setVisibility(View.VISIBLE);
                mIvWhiteBg.setVisibility(View.INVISIBLE);
                mIvBlueBg.setVisibility(View.INVISIBLE);
                mIvPinkBg.setVisibility(View.INVISIBLE);
                bs_preview.setImageResource(R.mipmap.main_x5_base_station_gray_icon);
                /**
                 * 切换机器人图片保存对应的key
                 */
                SharedPreferencesList.switchRobotPictureX5(activity, "switch", "gray", null, tmallDeviceId);
                // LogUtils.i(" 切换机器 颜色   switchRobotIcon rb_gray");
            }
        });
        rb_white.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                mIvGrayBg.setVisibility(View.INVISIBLE);
                mIvWhiteBg.setVisibility(View.VISIBLE);
                mIvBlueBg.setVisibility(View.INVISIBLE);
                mIvPinkBg.setVisibility(View.INVISIBLE);
                bs_preview.setImageResource(R.mipmap.robot_icon_pic_x5_white);
                /**
                 * 切换机器人图片保存对应的key
                 */
                SharedPreferencesList.switchRobotPictureX5(activity, "switch", "white", null, tmallDeviceId);
                // LogUtils.i(" 切换机器 颜色   switchRobotIcon rb_red");
            }
        });
        rb_blue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                mIvGrayBg.setVisibility(View.INVISIBLE);
                mIvWhiteBg.setVisibility(View.INVISIBLE);
                mIvBlueBg.setVisibility(View.VISIBLE);
                mIvPinkBg.setVisibility(View.INVISIBLE);
                bs_preview.setImageResource(R.mipmap.main_x5_base_station_red_icon);
                /**
                 * 切换机器人图片保存对应的key
                 */
                SharedPreferencesList.switchRobotPictureX5(activity, "switch", "blue", null, tmallDeviceId);
                // LogUtils.i(" 切换机器 颜色   switchRobotIcon rb_red");
            }
        });
        rb_pink.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                mIvGrayBg.setVisibility(View.INVISIBLE);
                mIvWhiteBg.setVisibility(View.INVISIBLE);
                mIvBlueBg.setVisibility(View.INVISIBLE);
                mIvPinkBg.setVisibility(View.VISIBLE);
                bs_preview.setImageResource(R.mipmap.main_x5_base_station_red_icon);
                /**
                 * 切换机器人图片保存对应的key
                 */
                SharedPreferencesList.switchRobotPictureX5(activity, "switch", "pink", null, tmallDeviceId);
                // LogUtils.i(" 切换机器 颜色   switchRobotIcon rb_red");
            }
        });

        //初始化PopupWindow对象
        popupWindow = new PopupWindow(contentview, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable());

        //让popupwindow在底部显示
        popupWindow.showAsDropDown(iv_baseStationSwitchRobot_Icon);

    }

    private void switchRobotTextColor(ImageView grayBg, ImageView whiteBg, ImageView blueBg, ImageView pinkBg) {
        SharedPreferences sp = activity.getSharedPreferences("X5_SP_ROBOT_ICON", activity.MODE_PRIVATE);//创建sp对象,如果有key为"SP_PEOPLE"的sp就取出
        String peopleListJson = sp.getString("X5_KEY_RobotIcon_LIST_DATA", "");  //取出key为"KEY_PEOPLE_DATA"的值，如果值为空，则将第二个参数作为默认值赋值
        if (peopleListJson != "")  //防空判断
        {
            Gson gson = new Gson();
            List<RobotIconColorBean> mList = gson.fromJson(peopleListJson, new TypeToken<List<RobotIconColorBean>>() {
            }.getType());//将json字符串转换成List集合
            if (mList.size() > 0) {
                String connect_deviceId = robot.getTmalDeviceId();
                for (int i = 0; i < mList.size(); i++) {
                    if (mList.get(i).getDeviceId().equals(connect_deviceId)) {
                        String color = mList.get(i).getIsICutoverColor();
                        LogUtils.i("设置颜色 ： " + color);
                        if (color != null) {
                            if ("gray".equals(color)) {
                                //灰色
                                grayBg.setVisibility(View.VISIBLE);
                                whiteBg.setVisibility(View.INVISIBLE);
                                blueBg.setVisibility(View.INVISIBLE);
                                pinkBg.setVisibility(View.INVISIBLE);
                            } else if ("white".equals(color)) {
                                //白色
                                grayBg.setVisibility(View.INVISIBLE);
                                whiteBg.setVisibility(View.VISIBLE);
                                blueBg.setVisibility(View.INVISIBLE);
                                pinkBg.setVisibility(View.INVISIBLE);
                            } else if ("blue".equals(color)) {
                                //蓝色
                                grayBg.setVisibility(View.INVISIBLE);
                                whiteBg.setVisibility(View.INVISIBLE);
                                blueBg.setVisibility(View.VISIBLE);
                                pinkBg.setVisibility(View.INVISIBLE);
                            } else if ("pink".equals(color)) {
                                //粉色
                                grayBg.setVisibility(View.INVISIBLE);
                                whiteBg.setVisibility(View.INVISIBLE);
                                blueBg.setVisibility(View.INVISIBLE);
                                pinkBg.setVisibility(View.VISIBLE);
                            } else {
                                grayBg.setVisibility(View.VISIBLE);
                                whiteBg.setVisibility(View.INVISIBLE);
                                blueBg.setVisibility(View.INVISIBLE);
                                pinkBg.setVisibility(View.INVISIBLE);
                            }
                        } else {
                            grayBg.setVisibility(View.VISIBLE);
                            whiteBg.setVisibility(View.INVISIBLE);
                            blueBg.setVisibility(View.INVISIBLE);
                            pinkBg.setVisibility(View.INVISIBLE);
                        }
                    }
                }
            } else {
                whiteBg.setVisibility(View.INVISIBLE);
                grayBg.setVisibility(View.VISIBLE);
                blueBg.setVisibility(View.INVISIBLE);
                pinkBg.setVisibility(View.INVISIBLE);
            }
        }
    }

    //处理滑动事件 展开折叠
    public void unfoldAnim(final View view, int duration) {
        ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) (view.getLayoutParams());
        if (isFolding) {
            return;
        }
        int unfoldTopmargin = DensityUtil.dip2px(getContext(), 28);

        ValueAnimator foldVerticalAnim = ValueAnimator.ofInt(v_light_color_bg.getHeight(), unfoldTopmargin);
        foldVerticalAnim.setDuration(duration);
        foldVerticalAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) (view.getLayoutParams());
//                params.height = (int) animation.getAnimatedValue();
                params.topMargin = (int) animation.getAnimatedValue();
                view.setLayoutParams(params);
            }
        });

        foldVerticalAnim.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                isFolding = true;
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                isFolding = false;
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                isFolding = false;
            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });

        foldVerticalAnim.start();
    }

    public void foldAnim(final View view, int duration) {
        ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) (view.getLayoutParams());
        LogUtils.i(" view : " + view.getHeight() + " isFolding: " + isFolding + " light_color_bg height: " + v_light_color_bg.getHeight());
        int unfoldTopmargin = DensityUtil.dip2px(getContext(), 28);
        if (isFolding || params.topMargin > unfoldTopmargin) {
            return;
        }

        ValueAnimator foldVerticalAnim = ValueAnimator.ofInt(unfoldTopmargin, v_light_color_bg.getHeight());
        foldVerticalAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) view.getLayoutParams();
                params.topMargin = (int) animation.getAnimatedValue();
                view.setLayoutParams(params);
            }

        });
        foldVerticalAnim.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                isFolding = true;
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                isFolding = false;
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                isFolding = false;
            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });

        foldVerticalAnim.setDuration(duration);
        foldVerticalAnim.start();
    }

    private void showBaseStationOfflineDialog() {
        Dialog dialog = new Dialog(getActivity());
        dialog.setContentView(R.layout.outlogin_dialog);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        dialog.setCanceledOnTouchOutside(false);
        TextView mBtnOutLoginConfirm = dialog.findViewById(R.id.btn_outLoginConfirm);
        TextView mBtnOutLoginCancel = dialog.findViewById(R.id.btn_outLoginCancel);
        TextView mTvDialogTitle = dialog.findViewById(R.id.tv_dialogTitle);
        TextView mTvDialogContent = dialog.findViewById(R.id.tv_content);
        View vLine = dialog.findViewById(R.id.main_view);
        mTvDialogTitle.setText(R.string.H_Host_NoResponse);
        mTvDialogContent.setText(R.string.H_Host_NoResponse_Tip);
        mBtnOutLoginConfirm.setText(getString(R.string.U_IKnow_Btn));
        mBtnOutLoginConfirm.setTextColor(getContext().getColor(R.color.text_color_blue));
        mBtnOutLoginCancel.setVisibility(View.GONE);
        vLine.setVisibility(View.GONE);
        mBtnOutLoginConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private void setGuideInterface() {
        //判断是否是第一次安装程序(给出指引界面)
        boolean value = SharedPrefsUtil.getValue(activity, "isBaseStationGuide", "isBaseStationGuide", false);
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (!value) {
                    int[] location_base = new int[2];
                    while (true) {
                        try {
                            Thread.sleep(300);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        iv_baseStationSwitchRobot_Icon.getLocationOnScreen(location_base);//得到相对当前控件的坐标位置
                        LogUtils.i(" : BaseStationFragment======= ======== location : " + location_base[0] + " , " + location_base[1]);
                        if (location_base[1] != 0) {
                            break;
                        }
                    }
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            LogUtils.i("指引界面 ------" + value);
                            SharedPrefsUtil.putValue(activity, "isBaseStationGuide", "isBaseStationGuide", true);
                            baseGuideDialog = new Dialog(activity);
                            baseGuideDialog.setContentView(R.layout.base_station_guide_dialog);
                            baseGuideDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
                            baseGuideDialog.setCanceledOnTouchOutside(false);
                            //设置全屏
                            baseGuideDialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);

                            baseStationGuideLayout01 = baseGuideDialog.findViewById(R.id.base_station_guide_layout01);
                            baseStationGuideLayout02 = baseGuideDialog.findViewById(R.id.base_station_guide_layout02);
                            baseStationGuideLayout03 = baseGuideDialog.findViewById(R.id.base_station_guide_layout03);
                            baseStationGuideLayout04 = baseGuideDialog.findViewById(R.id.base_station_guide_layout04);

                            int barHeight = getStatusBarHeight(activity);
//                            LogUtils.i(barHeight + " : BaseStationFragment======= ======== location : " + location_base[0] + " , " + location_base[1]);
                            baseStationGuideLayout01.setY(location_base[1] - barHeight);
                            baseStationGuideLayout01.setVisibility(View.VISIBLE);

                            baseStationGuideLayout01.setOnClickListener(activity);
                            baseStationGuideLayout02.setOnClickListener(activity);
                            baseStationGuideLayout03.setOnClickListener(activity);
                            baseStationGuideLayout04.setOnClickListener(activity);
                            baseGuideDialog.show();
                        }
                    });
                }
            }
        }).start();


    }

    private int getStatusBarHeight(Activity activity) {
        int resourceId = activity.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            return activity.getResources().getDimensionPixelSize(resourceId);
        }
        return 150;
    }

    public static class MainHandler extends Handler {
        SoftReference<BaseStationFragment> baseStationFragmentSoftReference;

        public MainHandler(BaseStationFragment fragment) {
            baseStationFragmentSoftReference = new SoftReference<>(fragment);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            LogUtils.i("msg " + msg.what);
            if (baseStationFragmentSoftReference.get() == null) {
                return;
            }
            if (msg.what == Event.MESSAGE_TYPE_GET_DEVICE_STATUS_DETAIL_REPEAT) {
                baseStationFragmentSoftReference.get().getDeviceStatusDetail();
            } else if (msg.what == Event.MESSAGE_TYPE_GET_DEVICE_STATUS_INFO) {
                baseStationFragmentSoftReference.get().getDeviceStatusInfo();
            } else if (msg.what == MSG_START_IN_1) {
                removeMessages(MSG_START_IN_2);
                removeMessages(MSG_START_IN_1);
                baseStationFragmentSoftReference.get().lav_aircleaner_in.playAnimation();
                sendEmptyMessageDelayed(MSG_START_IN_2, 2000);
            } else if (msg.what == MSG_START_IN_2) {
                removeMessages(MSG_START_IN_1);
                removeMessages(MSG_START_IN_2);
                baseStationFragmentSoftReference.get().lav_aircleaner_in_2.playAnimation();
                sendEmptyMessageDelayed(MSG_START_IN_1, 2000);
            } else if (msg.what == MSG_START_OUT_1) {
                removeMessages(MSG_START_OUT_1);
                removeMessages(MSG_START_OUT_2);
                baseStationFragmentSoftReference.get().lav_aircleaner_out.playAnimation();
                sendEmptyMessageDelayed(MSG_START_OUT_2, 2500);
            } else if (msg.what == MSG_START_OUT_2) {
                removeMessages(MSG_START_OUT_1);
                removeMessages(MSG_START_OUT_2);
                baseStationFragmentSoftReference.get().lav_aircleaner_out_2.playAnimation();
                sendEmptyMessageDelayed(MSG_START_OUT_1, 2500);
            }
        }
    }
}
